--[[
    desc: 新版风暴峡湾排行榜
    author:Hoo
    time:2022-03-07 15:58:24
]]

---@class UIChaosTestRankNew
local UIChaosTestRankNew = UIBase.New(PanelResNames.UIChaosTestRankNew)
local M = UIChaosTestRankNew

function M.Init()
    UIBase.Init(M)
end

---@protected
function M:OnCreate()
    self:RegisterOnClick(self:GetChild("BackButton"), self.onClickClose, self)

    self.topItem     = self:GetChild("Top1")
    self.listRank    = self:GetChild("RankList")
    self.txtTitle    = self:GetChild("Title")
    self.panelMyRank = self:GetChild("MyRank")
    self:SetDynamicList(self.listRank, self.rankItemRenderer, self)

    self:RegisterEvent(Config.EventType.Trials_Chaos_Work_Rank, self.refreshData, self)
end
---@protected
function M:OnEnable()
    self.cfgTrialsRank = dataTable.getDataTable("t_trialsrank")
    self.rewardMax = 0
    for k, v in pairs(self.cfgTrialsRank) do
        self.rewardMax = self.rewardMax + 1
    end

    TrialHandel.SendTrialsWorldRank()
    TrialHandel.SendTrialsRecordInfo()
end
---@protected
function M:OnDisable()
end
---@protected
function M:OnDestroy()
    self.recordDatas = nil
    self.cfgTrialsRank = nil
    self:UnRegisterEvent(Config.EventType.Trials_Chaos_Work_Rank, self.refreshData, self)
end

--- 战斗记录数据
---@private
function M:refreshData()
    local rankInfo = logicMgr.TrialsManager.GetWorkRank()
    if not rankInfo then return end

    ---@type TrialsRankInfo[] 排行数据
    self.rankDatas = rankInfo

    ---@type {level: number, workRank: number, damage: number, score: number}
    self.myRankData = logicMgr.TrialsManager.GetMyRankInfo()

    -- ui
    self:loadTopRank()
    self:loadRankList()
    self:loadMyRank()
end

--- 榜首
---@private
function M:loadTopRank()
    if not self.topItem then return end
    local rankData = self.rankDatas[1]
    local item     = self.topItem

    local ctrlPlayer = item:GetController("Player")
    local panelHead  = item:GetChild("RankHead")
    local headIcon   = panelHead:GetChild("head"):GetChild("HeadIcon")
    local headFrame  = panelHead:GetChild("frame")
    if not rankData then
        ctrlPlayer.selectedIndex = 1
        headIcon.url = nil
        return
    end

    local txtName  = item:GetChild("PlayerName")
    local txtPoint = item:GetChild("PlayerPoint")

    ctrlPlayer.selectedIndex = 0
    panelHead:GetController("first").selectedIndex = 1
    headIcon.url  = logicMgr.SkinManager.GetHeroIconBySkinId(rankData.playerShowInfo.pic)
    headFrame.url = EnumConst.AtlasPath.ICONAtlas .. rankData.playerShowInfo.picFrame
    txtPoint.text = string.format(getLanguage("UIChaosTestPoint"), getNumString(tonumber(tostring(rankData.score))))
    txtName.text  = rankData.playerShowInfo.name

    -- 头像点击事件
    panelHead.onClick:Clear();
    panelHead.onClick:Add(function()
        if tostring(rankData.playerShowInfo.playerId) == logicMgr.HeroManager.GetRoleId() then
            return
        end
        roleInfoHandler.sendreqOtherRoleInfo(rankData.playerShowInfo.playerId)
    end)
    
    -- 战斗记录
    local btnRecord = item:GetChild("Record")
    btnRecord.onClick:Clear()
    btnRecord.onClick:Add(function()
        if rankData.record then
            showUI(PanelNames.UILevelRecode, EnumConst.FightTypeConst.TRIAL, rankData.record)
        else
            UISysTips.AddMsg(getLanguage("ChaoError1"))
        end
    end)

    -- 奖励
    self:showRankReward(item:GetChild("RewardList"), 1)
end

--- 排行榜列表
---@private
function M:loadRankList()
    self.listRank.numItems = Config.Const_Rank_Max_Num - 1
end

--- 自己排名
---@private
function M:loadMyRank()
    local item = self.panelMyRank
    if not item then return end

    local ctrlEmpty   = item:GetController("empty")
    local ctrlRanking = item:GetController("ranking")
    local rankData = self.myRankData
    if not rankData then
        ctrlEmpty.selectedIndex = 1
        return 
    end

    local myInfo   = G.serverData["roleInfo"].show
    local txtRank  = item:GetChild("Rank")
    local txtName  = item:GetChild("PlayerName")
    local txtPoint = item:GetChild("PlayerPoint")

    local panelHead = item:GetChild("Head");
    local headIcon  = panelHead:GetChild("head"):GetChild("HeadIcon")
    local headFrame = panelHead:GetChild("frame")

    ctrlEmpty.selectedIndex = 0
    ctrlRanking.selectedIndex = rankData.workRank > 3 and 3 or rankData.workRank - 1
    headIcon.url  = logicMgr.SkinManager.GetHeroIconBySkinId(myInfo.pic)
    headFrame.url = EnumConst.AtlasPath.ICONAtlas .. myInfo.picFrame
    txtRank.text  = rankData.workRank < 1000 and rankData.workRank .. '' or '999+'
    txtName.text  = myInfo.name
    txtPoint.text = string.format(getLanguage("UIChaosTestPoint"), getNumString(rankData.score))

    -- 未上榜
    if rankData.workRank <= 0 then
        ctrlRanking.selectedIndex = 3
        txtRank.text = getLanguage("NotInRank")
    end
    
    -- 战斗记录
    local btnRecord  = item:GetChild("Record")
    btnRecord.onClick:Clear()
    btnRecord.onClick:Add(function()
        local recodeData = logicMgr.TrialsManager.GetTrialsRecordInfo()
        if recodeData.records ~= nil and recodeData.records[1] then
            showUI(PanelNames.UILevelRecode, EnumConst.FightTypeConst.TRIAL, recodeData.records[1])
        else
            UISysTips.AddMsg(getLanguage("ChaoTips2"))
        end
    end)

    -- 奖励
    self:showRankReward(item:GetChild("RewardList"), rankData.workRank)
end

--- 记录战斗列表
---@private
---@param index number  索引
---@param obj   GObject 记录战斗item对象
function M:rankItemRenderer(index, obj)
    local ctrlEmpty   = obj:GetController("empty")
    local ctrlRanking = obj:GetController("ranking")
    ctrlRanking.selectedIndex = index > 2 and 3 or index

    local rank = index + 1
    local rankData = self.rankDatas[rank]
    if not rankData then
        ctrlEmpty.selectedIndex = 1
        return 
    end

    local txtRank  = obj:GetChild("Rank")
    local txtName  = obj:GetChild("PlayerName")
    local txtPoint = obj:GetChild("PlayerPoint")

    local panelHead = obj:GetChild("Head");
    local headIcon  = panelHead:GetChild("head"):GetChild("HeadIcon")
    local headFrame = panelHead:GetChild("frame")

    ctrlEmpty.selectedIndex = 0
    headIcon.url  = logicMgr.SkinManager.GetHeroIconBySkinId(rankData.playerShowInfo.pic)
    headFrame.url = EnumConst.AtlasPath.ICONAtlas .. rankData.playerShowInfo.picFrame
    txtRank.text  = rank .. ''
    txtName.text  = rankData.playerShowInfo.name
    txtPoint.text = string.format(getLanguage("UIChaosTestPoint"), getNumString(tonumber(tostring(rankData.score))))

    -- 头像点击事件
    panelHead.onClick:Clear();
    panelHead.onClick:Add(function()
        if tostring(rankData.playerShowInfo.playerId) == logicMgr.HeroManager.GetRoleId() then
            return
        end
        roleInfoHandler.sendreqOtherRoleInfo(rankData.playerShowInfo.playerId)
    end)
    
    -- 战斗记录
    local btnRecord = obj:GetChild("Record")
    btnRecord.onClick:Clear()
    btnRecord.onClick:Add(function()
        if rankData.record then
            showUI(PanelNames.UILevelRecode, EnumConst.FightTypeConst.TRIAL, rankData.record)
        else
            UISysTips.AddMsg(getLanguage("ChaoError1"))
        end
    end)

    -- 奖励
    self:showRankReward(obj:GetChild("RewardList"), rank)
end

--- 显示排名奖励列表
---@private
---@param listObj GList  列表组件
---@param rank    number 排名
function M:showRankReward(listObj, rank)
    if listObj == nil or self.cfgTrialsRank == nil then return end
    if rank <= 0 then rank = self.rewardMax end

    local rewardIndex = math.min(self.rewardMax, rank)
    local cfgReward   = self.cfgTrialsRank[tostring(rewardIndex)]
    local rewardData  = decodeJsonStrToTabel(cfgReward['f_Reward'])
    logicMgr.CostManager.RefreshItemList(listObj, rewardData)
end

--- 关闭界面
---@private
function M:onClickClose()
    closeUI(PanelResNames.UIChaosTestRankNew)
end

return M
